#!/usr/bin/env python
# -*- coding: UTF-8 -*-
#Author: alvayang <alvayang@tabex.org>
#Last Change: 
#Description: 


import sys,os
sys.path.insert(0, os.getcwd())
from twisted.internet import reactor,protocol,defer
from twisted.web import http
from twisted.protocols import basic
from twisted.application import internet,service
from twisted.internet import defer
from twisted.python import log,logfile

import constants
import utils

from lib import db

class httpRequestFactory(http.Request):
    def process(self):
        self.channel.map["/"] = self.channel.map['/index']
        self.channel.keys.append('/')
        req_path = self.path.strip()
        if req_path in self.channel.keys:
            opt_obj = self.channel.map[req_path]
            do_func = 'do_' + self.method
            func = getattr(opt_obj, do_func, None)
            self.setHeader('Content-Type', 'text/html; charset=utf-8')
            self.setHeader('Cache-Control', 'no-cache')
            if func:
                self.msg_db = self.channel.db
                d = defer.Deferred()
                d.addCallback(self.render_data)
                d.addErrback(self.close)
                setattr(opt_obj, 'write', d.callback)
                setattr(opt_obj, 'error', d.errback)
                func(self)
            else:
                #TODO: 这里应该是个漂亮的错误页面.
                pass
        else:
            #TODO: 这里应该是个漂亮的错误页面.
            self.close()

    def render_data(self, result):
        self.write(str(result))
        self.close()

    def close(self, reason = None):
        if reason:
            # debug 开,正是服务器上还是要关掉这两行滴
            # pass # online
            self.write(str(reason)) #debug
        self.finish()

class httpRequestChannel(http.HTTPChannel):
    def __init__(self, res, db):
        http.HTTPChannel.__init__(self)
        self.map = res
        self.keys = self.map.keys()
        self.db = db
        self.requestFactory = httpRequestFactory

class httpServerFactory(http.HTTPFactory):
    def __init__(self, protocol, res):
        self.protocol = protocol
        self.map =  res

    def buildProtocol(self, addr):
        odb = db.GFMSGDB(os.path.join(os.getcwd(), 'db'))
        p = self.protocol(self.map, odb)
        return p


if __name__ == "__main__":
    pass
else:
    modules = [(x[:-3], os.path.join('app', x)) for x in os.listdir('app') if x.endswith('.py')]
    res = utils.import_modules(modules)
    from twisted.application import internet,service,app
    app.logfile.LogFile = logfile.DailyLogFile
    application = service.Application('blogService')
    blog_service = internet.TCPServer(constants.HTTPPORT, \
            httpServerFactory(httpRequestChannel, res))
    blog_service.setServiceParent(application)

